package com.seadragon.apps.doctorcard.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.seadragon.apps.doctorcard.model.DoctorCardConstants;
import com.seadragon.apps.doctorcard.model.Contact;



public class AccessControlInterceptor extends HandlerInterceptorAdapter{
	private List<String> publicUrls; //list of url patterns that are not required for user login
	@Override
	public boolean preHandle(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler) throws Exception {
		Contact contactInSession = (Contact)request.getSession().getAttribute(DoctorCardConstants.SESSION_SCOPED_CONTACT);
		String uri = request.getRequestURI();
		if (contactInSession==null){
			for (String publicUrl : publicUrls) {
				if (uri.indexOf(publicUrl)>-1){
					return true;
				} 
			}
			//if the uri doesn't match any of the public urls, send 401
			response.sendError(HttpServletResponse.SC_UNAUTHORIZED);//401
			return false;
		}
		return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler,
            ModelAndView mav) throws Exception {

    }

	public List<String> getPublicUrls() {
		return publicUrls;
	}

	public void setPublicUrls(List<String> publicUrls) {
		this.publicUrls = publicUrls;
	}
}
